<?php
// 获取正确情况的CSS类名函数
function getCorrectnessClass($correctness) {
    switch($correctness) {
        case '正确':
            return 'text-success';
        case '错误':
            return 'text-danger';
        case '不完全正确':
            return 'text-warning';
        case '未批改':
        default:
            return 'text-secondary';
    }
}

// 截断文本函数
function truncateText($text, $length = 20) {
    if (empty($text)) return '';
    if (strlen($text) <= $length) return $text;
    return substr($text, 0, $length) . '...';
}

// 记录列表组件
function renderRecordList($conn) {
    // 处理导入CSV功能
    $import_result = handleImportCSV($conn);
    
    // 构建筛选查询
    $filter_result = buildFilterQuery($conn);
    $filter_conditions = $filter_result['conditions'];
    $params = $filter_result['params'];
    $types = $filter_result['types'];
    
    // 处理分页参数
    $page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? (int)$_GET['page'] : 1;
    $per_page_options = [10, 20, 50, 100];
    $default_per_page = 20;
    $per_page = isset($_GET['per_page']) && in_array((int)$_GET['per_page'], $per_page_options) ? (int)$_GET['per_page'] : $default_per_page;
    $offset = ($page - 1) * $per_page;
    
    // 构建基础查询
    $base_sql = "SELECT e.*, es.name as exercise_set_name, c.name as chapter_name 
                FROM exam_records e
                LEFT JOIN exercise_sets es ON e.exercise_set_id = es.id
                LEFT JOIN chapters c ON e.chapter_id = c.id";
    
    // 添加筛选条件
    if (!empty($filter_conditions)) {
        $base_sql .= " WHERE " . implode(" AND ", $filter_conditions);
    }
    
    // 计算记录总数
    $count_sql = "SELECT COUNT(*) as total " . substr($base_sql, strpos($base_sql, "FROM"));
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($params)) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $record_count = $count_result->fetch_assoc()['total'];
    $count_stmt->close();
    
    // 获取分页数据
    $sql = $base_sql . " ORDER BY exam_date DESC, start_time DESC LIMIT ? OFFSET ?";
    $stmt = $conn->prepare($sql);
    
    // 添加LIMIT和OFFSET参数
    if (!empty($params)) {
        $params[] = $per_page;
        $params[] = $offset;
        $types .= "ii";
        $stmt->bind_param($types, ...$params);
    } else {
        $stmt->bind_param("ii", $per_page, $offset);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    // 计算总页数
    $total_pages = ceil($record_count / $per_page);
    
    // 构建GET参数字符串
    $get_params = '';
    foreach ($_GET as $key => $value) {
        if ($key != 'tab' && $key != 'page' && $key != 'per_page') {
            $get_params .= '&' . urlencode($key) . '=' . urlencode($value);
        }
    }
    
    // 导入结果提示信息
    $messageHtml = '';
    if (!empty($import_result['error'])) {
        $messageHtml = '<div class="alert alert-danger mt-3 mb-3">' . $import_result['error'] . '</div>';
    } else if (!empty($import_result['success'])) {
        $messageHtml = '<div class="alert alert-success mt-3 mb-3">' . $import_result['success'] . '</div>';
    }
    
    ob_start();
    ?>
    <div class="card">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h3>记录列表</h3>
                <div class="d-flex gap-2">
                    <!-- 导入按钮，点击显示导入表单 -->
                    <button class="btn btn-primary" onclick="document.getElementById('import-form-container').style.display = 'block'">导入记录</button>
                    <a href="index.php?export&tab=list" class="btn btn-success">导出所有记录</a>
                </div>
            </div>
        </div>
        <div class="card-body">
            <!-- 导入表单（默认隐藏） -->
            <div id="import-form-container" class="mb-4" style="display: none;">
                <div class="card bg-light">
                    <div class="card-body">
                        <h4>导入记录</h4>
                        <p class="text-muted">请上传CSV格式的文件，确保列顺序与导出的一致。</p>
                        <form action="index.php?tab=list" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="csv_file">选择CSV文件:</label>
                                <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv,.xlsx,.xls" required>
                            </div>
                            <button type="submit" class="btn btn-primary mt-2">上传导入</button>
                            <button type="button" class="btn btn-secondary mt-2" onclick="document.getElementById('import-form-container').style.display = 'none'">取消</button>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- 导入结果提示 -->
            <?php echo $messageHtml; ?>
            <!-- 分页控制区域 -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <!-- 显示搜索结果数量 -->
                <div class="result-count">
                    共找到 <strong><?php echo $record_count; ?></strong> 条记录
                </div>
                
                <!-- 每页条目数量选择器 -->
                <div class="per-page-selector">
                    <form method="get" class="d-flex align-items-center gap-2" style="flex-wrap: nowrap;">
                        <input type="hidden" name="tab" value="list">
                        <?php
                        // 保留其他GET参数
                        foreach ($_GET as $key => $value) {
                            if ($key != 'tab' && $key != 'per_page' && $key != 'page') {
                                echo '<input type="hidden" name="' . htmlspecialchars($key) . '" value="' . htmlspecialchars($value) . '">';
                            }
                        }
                        ?>
                        <label for="per_page" style="white-space: nowrap; margin-bottom: 0;">每页显示:</label>
                        <select name="per_page" id="per_page" class="form-select form-select-sm" onchange="this.form.submit()">
                            <option value="10"<?php echo ($per_page == 10 ? ' selected' : ''); ?>>10条</option>
                            <option value="20"<?php echo ($per_page == 20 ? ' selected' : ''); ?>>20条</option>
                            <option value="50"<?php echo ($per_page == 50 ? ' selected' : ''); ?>>50条</option>
                            <option value="100"<?php echo ($per_page == 100 ? ' selected' : ''); ?>>100条</option>
                        </select>
                    </form>
                </div>
            </div>
            <div class="table-responsive">
                <style>
                /* 确保表格列名水平显示 */
                .table th {
                    white-space: nowrap;
                    text-align: center;
                    vertical-align: middle;
                    max-width: 150px;
                    height: auto !important;
                    padding: 10px 8px;
                    border: 1px solid #dee2e6 !important;
                }
                
                /* 确保表格内容也能正常显示 */
                .table td {
                    vertical-align: middle;
                    padding: 8px;
                    border: 1px solid #dee2e6 !important;
                }
                
                /* 为表格添加网格线 */
                .table {
                    border-collapse: collapse !important;
                    border-spacing: 0 !important;
                    border: 1px solid #dee2e6;
                }
                
                .table th,
                .table td {
                    border: 1px solid #dee2e6 !important;
                }
                
                /* 对于可能较长的文本，截断显示并添加鼠标样式 */
                .table td:nth-child(10), 
                .table td:nth-child(11), 
                .table td:nth-child(12) {
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    max-width: 120px;
                    cursor: pointer;
                    position: relative;
                }
                
                .table td.text-ellipsis:hover {
                    color: #0d6efd;
                    text-decoration: underline;
                }
                </style>
                <table class="table table-bordered table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>日期</th>
                            <th>做题方式</th>
                            <th>习题集</th>
                            <th>章节</th>
                            <th>题号</th>
                            <th>做题时间</th>
                            <th>耗时(分钟)</th>
                            <th>正确情况</th>
                            <th>备注</th>
                            <th>错因</th>
                            <th>反思</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $has_records = false;
                        while ($row = $result->fetch_assoc()) {
                            $has_records = true;
                            $exercise_set_name = isset($row['exercise_set_name']) && $row['exercise_set_name'] ? $row['exercise_set_name'] : '未知习题集';
                            $chapter_name = isset($row['chapter_name']) && $row['chapter_name'] ? $row['chapter_name'] : '未知章节';
                            $record_info = htmlspecialchars($row['exam_date'] . ' ' . $row['question_type'] . ' ' . $exercise_set_name . '-' . $chapter_name . '-' . $row['question_number'], ENT_QUOTES);
                            ?>
                            <tr>
                                <td><?php echo $row['id']; ?></td>
                                <td><?php echo $row['exam_date']; ?></td>
                                <td><?php echo $row['question_type']; ?></td>
                                <td><?php echo $exercise_set_name; ?></td>
                                <td><?php echo $chapter_name; ?></td>
                                <td><?php echo $row['question_number']; ?></td>
                                <td><?php echo $row['start_time']; ?> - <?php echo $row['end_time']; ?></td>
                                <td><?php echo $row['duration']; ?></td>
                                <td class="<?php echo getCorrectnessClass($row['correctness']); ?>"><?php echo $row['correctness']; ?></td>
                                <td class="text-ellipsis" title="点击查看详细内容" data-content="<?php echo htmlspecialchars($row['notes'], ENT_QUOTES); ?>" data-field="备注" onclick="showFullContent(this)"><?php echo truncateText($row['notes'], 20); ?></td>
                                <td class="text-ellipsis" title="点击查看详细内容" data-content="<?php echo htmlspecialchars($row['error_reason'], ENT_QUOTES); ?>" data-field="错因" onclick="showFullContent(this)"><?php echo truncateText($row['error_reason'], 20); ?></td>
                                <td class="text-ellipsis" title="点击查看详细内容" data-content="<?php echo htmlspecialchars($row['reflection'], ENT_QUOTES); ?>" data-field="反思" onclick="showFullContent(this)"><?php echo truncateText($row['reflection'], 20); ?></td>
                                <td>
                                    <a href="index.php?edit=<?php echo $row['id']; ?>&tab=add" class="btn btn-sm btn-warning mb-1">编辑</a>
                                    <button type="button" class="btn btn-sm btn-danger mb-1" data-bs-toggle="modal" data-bs-target="#deleteModal" data-record-id="<?php echo $row['id']; ?>" data-record-info="<?php echo $record_info; ?>">删除</button>
                                </td>
                            </tr>
                        <?php }
                        if (!$has_records) {
                            ?>
                            <tr>
                                <td colspan="13" class="text-center">暂无记录</td>
                            </tr>
                        <?php }
                        ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页导航 -->
            <?php if ($total_pages > 1) {
                // 预定义所有变量，避免作用域问题
                $prev_page = $page - 1;
                $prev_disabled = $page <= 1 ? 'disabled' : '';
                $prev_url = $page <= 1 ? '#' : 'index.php?tab=list&page=' . $prev_page . '&per_page=' . $per_page . $get_params;
                
                // 页码计算
                $max_pages_to_show = 5;
                $start_page = max(1, $page - floor($max_pages_to_show / 2));
                $end_page = min($total_pages, $start_page + $max_pages_to_show - 1);
                
                // 调整起始页码以确保显示足够的页码
                if ($end_page - $start_page + 1 < $max_pages_to_show) {
                    $start_page = max(1, $end_page - $max_pages_to_show + 1);
                }
                
                // 第一页和省略号
                $first_page_url = 'index.php?tab=list&page=1&per_page=' . $per_page . $get_params;
                
                // 最后一页
                $last_page_url = 'index.php?tab=list&page=' . $total_pages . '&per_page=' . $per_page . $get_params;
                
                // 下一页
                $next_page = $page + 1;
                $next_disabled = $page >= $total_pages ? 'disabled' : '';
                $next_url = $page >= $total_pages ? '#' : 'index.php?tab=list&page=' . $next_page . '&per_page=' . $per_page . $get_params;
                
                echo '<div class="pagination-container mt-4">
                    <nav aria-label="分页导航">
                        <ul class="pagination justify-content-center">
                            <!-- 上一页 -->
                            <li class="page-item ' . $prev_disabled . '">
                                <a class="page-link" href="' . $prev_url . '" aria-label="上一页">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>';
                        
                        // 第一页和省略号
                        if ($start_page > 1) {
                            echo '<li class="page-item"><a class="page-link" href="' . $first_page_url . '">1</a></li>';
                            if ($start_page > 2) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                        }
                        
                        // 页码
                        for ($i = $start_page; $i <= $end_page; $i++) {
                            $page_url = 'index.php?tab=list&page=' . $i . '&per_page=' . $per_page . $get_params;
                            $active = $page == $i ? 'active' : '';
                            echo '<li class="page-item ' . $active . '"><a class="page-link" href="' . $page_url . '">' . $i . '</a></li>';
                        }
                        
                        // 最后一页和省略号
                        if ($end_page < $total_pages) {
                            if ($end_page < $total_pages - 1) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                            echo '<li class="page-item"><a class="page-link" href="' . $last_page_url . '">' . $total_pages . '</a></li>';
                        }
                        
                        // 下一页
                        echo '<li class="page-item ' . $next_disabled . '">
                            <a class="page-link" href="' . $next_url . '" aria-label="下一页">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>';
            }
            ?>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-md">
            <div class="modal-content shadow-xl border-0 rounded-2xl transition-all duration-300">
                <div class="modal-header" style="background: linear-gradient(135deg, #475569, #1e293b); color: white; border-bottom: none; padding: 1.5rem;">
                    <div class="d-flex align-items-center gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-exclamation-triangle" viewBox="0 0 16 16">
                            <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
                        </svg>
                        <h5 class="modal-title mb-0" id="deleteModalLabel" style="font-weight: 600; font-size: 1.25rem; color: #fff;">确认删除</h5>
                    </div>
                    <button type="button" class="btn-close" style="background-color: rgba(255,255,255,0.3); opacity: 1;" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-6" style="background-color: #fff;">
                    <p class="text-center mb-4" style="font-size: 1.1rem; color: #495057; font-weight: 500;">您确定要删除以下记录吗？</p>
                    <div class="card shadow-sm" style="background-color: #f8f9fa; border: 1px solid #e9ecef; border-radius: 0.75rem; padding: 1.25rem; margin-bottom: 1.5rem;">
                        <p id="deleteRecordInfo" class="text-center font-medium" style="color: #495057; line-height: 1.6;"></p>
                    </div>
                    <div class="alert alert-danger text-center p-3 mb-0" style="border: none; border-radius: 0.5rem;">
                        <p class="mb-0 text-danger" style="font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 0.5rem;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-exclamation-circle" viewBox="0 0 16 16">
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z"/>
                            </svg>
                            此操作不可撤销，删除后数据将无法恢复！
                        </p>
                    </div>
                </div>
                <div class="modal-footer border-top-0 justify-content-center gap-4 p-5" style="background-color: #f8f9fa;">
                    <button type="button" class="btn px-6 py-2.5 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5" data-bs-dismiss="modal">
                        取消
                    </button>
                    <a href="" id="confirmDeleteBtn" class="btn px-6 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                        <span class="d-flex align-items-center gap-1">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
                                <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
                                <path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
                            </svg>
                            确认删除
                        </span>
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 详细内容显示模态框 -->
    <div class="modal fade" id="contentModal" tabindex="-1" aria-labelledby="contentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content shadow-xl border-0 rounded-2xl transition-all duration-300">
                <div class="modal-header" style="background: linear-gradient(135deg, #475569, #1e293b); color: white; border-bottom: none; padding: 1.5rem;">
                    <div class="d-flex align-items-center gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-card-text" viewBox="0 0 16 16">
                            <path d="M14.5 3a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5H14zm-13-1A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13z"/>
                            <path d="M3 5.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 8a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 8zm0 2.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5z"/>
                        </svg>
                        <h5 class="modal-title mb-0" id="contentModalLabel" style="font-weight: 600; font-size: 1.25rem; color: #fff;">详细内容</h5>
                    </div>
                    <button type="button" class="btn-close" style="background-color: rgba(255,255,255,0.3); opacity: 1;" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-6" style="background-color: #fff; min-height: 200px;">
                    <div class="mb-4">
                        <span class="badge bg-primary text-white px-3 py-1 rounded-full text-sm font-medium" id="contentFieldName"></span>
                    </div>
                    <div class="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
                        <pre id="contentDetails" style="white-space: pre-wrap; word-wrap: break-word; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif; line-height: 1.6; font-size: 1rem; margin: 0; color: #333; max-height: 400px; overflow-y: auto; padding: 1rem; background-color: #f8f9fa; border-radius: 0.5rem; border: 1px solid #e9ecef;"></pre>
                    </div>
                </div>
                <div class="modal-footer border-top-0 justify-content-center p-5" style="background-color: #f8f9fa;">
                    <button type="button" class="btn px-6 py-2.5 bg-gray-800 hover:bg-gray-900 text-white rounded-lg transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5" data-bs-dismiss="modal">
                        <span class="d-flex align-items-center gap-1">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle" viewBox="0 0 16 16">
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z"/>
                            </svg>
                            关闭
                        </span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 显示完整内容的函数
        function showFullContent(element) {
            const content = element.getAttribute('data-content');
            const field = element.getAttribute('data-field');
            
            document.getElementById('contentFieldName').textContent = field;
            document.getElementById('contentDetails').textContent = content || '无内容';
            
            const contentModal = new bootstrap.Modal(document.getElementById('contentModal'));
            contentModal.show();
        }
    </script>
    
    <script>
        // 初始化删除模态框
        document.addEventListener('DOMContentLoaded', function() {
            const deleteModal = document.getElementById('deleteModal');
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            const deleteRecordInfo = document.getElementById('deleteRecordInfo');
            
            deleteModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const recordId = button.getAttribute('data-record-id');
                const recordInfo = button.getAttribute('data-record-info');
                
                // 设置删除链接和显示信息
                confirmDeleteBtn.href = 'index.php?delete=' + recordId + '&tab=list';
                deleteRecordInfo.textContent = recordInfo;
            });
        });
    </script>
    <?php
    
    $listHtml = ob_get_clean();
    $stmt->close();
    return $listHtml;
}